/* eslint-disable import/no-dynamic-require */
const path_ = eval('require')('path');
const eventClass = require('./eventClass');
const fs = eval('require')('fs');
const mysql = require('./../utils/mysql');
const {
    basePath,
} = require('./../../../../foreEndApi/rebasePath')();

const mysqlConfPath = path_.join(basePath, 'node.mysql.json');

class mysqlClass extends eventClass {
    constructor() {
        super('mysqlClass');
        this.config = null;
        this.mysql = null;
        this.checkConfig(() => {});
    }

    configPath(cb) {
        this.returnMethod(cb, { data: mysqlConfPath });
    }

    checkConfig(cb) {
        if (fs.existsSync(mysqlConfPath)) {
            let err = null;
            try {
                this.config = JSON.parse(fs.readFileSync(mysqlConfPath, 'utf-8'));
                this.mysql = new mysql(this.config);
            } catch (e) {
                err = e;
            } finally {
                this.returnMethod(cb, { err });
            }
        } else {
            // fs.writeFileSync(mysqlConfPath, '{}');
            this.config = null;
            this.returnMethod(cb, {
                err: this.config ? null : '找不到配置',
                data: mysqlConfPath,
            });
        }
    }

    checkConnection(cb) {
        if (this.mysql) {
            this.mysql.query({
                sql: 'select 1',
            }, (err, data) => {
                this.returnMethod(cb, { err, data });
            });
        } else {
            this.returnMethod(cb, {
                err: '请先加成配置信息',
            });
        }
    }

    query(cb, { sql }) {
        if (this.mysql) {
            this.mysql.query({
                sql,
            }, (err, data) => {
                this.returnMethod(cb, { err, data });
            });
        } else {
            this.returnMethod(cb, { err: 'mysql 为初始化' });
        }
    }
}

module.exports = mysqlClass;
